<?php


namespace app\api\controller\User;


use app\api\controller\AppController;
use app\api\model\User\UserWalletModel;
use app\api\model\User\UserWithdrawModel;
use app\Request;
use app\Utils\StrUtil;
use app\Utils\Util;
use think\facade\Db;

class UserWithdraw extends AppController
{

    /**
     * @api {get} /get_user_withdraw_list 提现列表
     * @apiGroup 用户
     * @apiParam {int} page 页码
     * @apiParam {int} limit 数据条数
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccessExample {json} 部分数据
     * {
     *   "amount":"提现金额",
     *   "status":"状态 1审核中 5已提现 10提现失败",
     *   "type":"提现到 2:支付宝 3：微信",
     *   "handle_time":"处理时间",
     *   "remark":"描述",
     *   "add_time":"申请时间",
     * }
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getUserWithdrawList(Request $request)
    {
        $param = $request->param();
        $where = [];
        $page = !empty($param['page']) ? $param['page'] : 1;
        $limit = !empty($param['limit']) ? $param['limit'] : 10;

        $list = UserWithdrawModel::getUserWithdrawListWhere($page, $limit, $where);
        $count = UserWithdrawModel::getUserWithdrawCountWhere($where);
        return Util::returnPageJson(self::CODE_SUCCESS, $count, $list, "");
    }

    /**
     * @api {get} /get_withdraw 申请提现
     * @apiGroup 用户
     * @apiParam {int} amount 提现金额
     * @apiParam {int} type 提现到  2:支付宝 3：微信
     * @apiSuccess {int} code 状态码 0：正常 -1：错误
     * @apiSuccess {json} data 数据源
     * @apiSuccess {string} msg 描述
     * @apiVersion 1.0.0
     */
    public function getWithdraw(Request $request)
    {
        $param = $request->param();
        $user = $this->user;
        if(!empty($user)){
            Util::returnJson(self::CODE_ERROR,null,"请登录");
        }
        $data = [
            'uid'      => $user['id'],
            'amount'   => $param['amount'],
            'status'   => 1,
            'type'     => $param['type'],
            'add_time' => date("Y-m-d H:i:s",time())
        ];
        Db::startTrans();
        try {
            $id = UserWithdrawModel::addUserWithdraw($data);
            if($id){
                //扣除余额
                UserWalletModel::walletOut($user['id'],$param['amount'],StrUtil::BILL_USE_TYPE['WITHDRAWAL'],"用户提现");
                Db::commit();
                return Util::returnJson(self::CODE_SUCCESS,null,"提交成功！");
            }else{
                Db::rollback();
                return Util::returnJson(self::CODE_SUCCESS,null,"提交失败！");
            }
        }catch (\Exception $e){
            Db::rollback();
            return Util::returnJson(self::CODE_SUCCESS,null,"提交失败！");
        }
    }

}